<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>聊天室</title>
    <style>
        ul {
            list-style: none;
            height: 300px;
            width: 400px;
            overflow: scroll;
        }

        li {
            margin: 10px;
        }

        input {
            width: 100px;
            height: 50px;
        }
    </style>
    <script>
        var socket = null
        var clkNum = 0
        window.onload = function () {
            if (!socket) {
                //连接聊天服务器
                socket = new WebSocket('ws://localhost:3000/chatTest')       //连接地址必须和服务器设置一致
            }
            //连接聊天室成功时执行的方法
            socket.addEventListener('open', function (event) {
                console.log('socket is open')
            });
            //注册聊天事件,设置接收服务器聊天信息的处理
            socket.addEventListener('message', function (obj) {
                console.log('服务器发来的消息是：' + obj.data)
                var btn = document.querySelector('input')
                if (obj.data == '限时秒杀将在1秒后结束') {
                    btn.disabled = false
                    btn.value = '开始抢购'
                } else if (obj.data == '活动已结束') {
                    btn.disabled = true
                    btn.value = '活动已结束'
                }
                var ul = document.querySelector('ul')
                ul.innerHTML += '<li>' + obj.data + '</li>'
            })
        }
        function clk() {
            clkNum++
            //事件只能执行一次
            if (clkNum == 1) {
                socket.send(JSON.stringify({ msg: '该用户在时限内点击了按钮' }))
                var ul = document.querySelector('ul')
                ul.innerHTML += '<li>已抢到</li>'
            }
        }
    </script>
</head>

<body>
    <ul id="message">

    </ul>
    <form action="">
        <input type="button" id="btnChat" value="即将开始" disabled onclick="clk()">
    </form>
</body>

</html>